/*
 * @Description: 虚线
 * @Version: V1.0.0
 * @Author: 黄鑫
 * @Date: 2024-08-19 15:23:10
 * @LastEditors: 黄鑫
 * @LastEditTime: 2024-08-20 09:01:49
 * @FilePath: DashedLine.dart
 * @Props: 
 * @Remarks: 
 */
import 'package:flutter/material.dart';

class DashedLine extends StatelessWidget {
  // 虚线颜色
  final Color color;
  // 虚线长度
  final double dashLength;
  // 虚线间隔
  final double dashGap;
  // 虚线宽度
  final double lineWith;
  final Axis direction;

  const DashedLine({
    super.key,
    required this.color,
    this.dashLength = 4,
    this.dashGap = 4,
    this.lineWith = 1,
    this.direction = Axis.horizontal, // 默认方向为横向
  });

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      size: direction == Axis.horizontal
          ? Size(double.infinity, lineWith) // 横向虚线
          : Size(lineWith, double.infinity), // 纵向虚线
      painter: DashedLinePainter(
        color: color,
        dashLength: dashLength,
        dashGap: dashGap,
        lineWith: lineWith,
        direction: direction,
      ),
    );
  }
}

class DashedLinePainter extends CustomPainter {
  final Color color;
  final double dashLength;
  final double dashGap;
  final double lineWith;
  final Axis direction;

  DashedLinePainter({
    required this.color,
    required this.dashLength,
    required this.dashGap,
    required this.lineWith,
    required this.direction,
  });

  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..color = color
      ..strokeWidth = lineWith
      ..style = PaintingStyle.stroke;

    if (direction == Axis.horizontal) {
      double startX = 0;
      while (startX < size.width) {
        canvas.drawLine(
          Offset(startX, 0),
          Offset(startX + dashLength, 0),
          paint,
        );
        startX += dashLength + dashGap;
      }
    } else {
      double startY = 0;
      while (startY < size.height) {
        canvas.drawLine(
          Offset(0, startY),
          Offset(0, startY + dashLength),
          paint,
        );
        startY += dashLength + dashGap;
      }
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }
}
